# -*- encoding: utf-8 -*-
##############################################################################
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see http://www.gnu.org/licenses/.
#
##############################################################################

from odoo import models, fields, api
from odoo.tools.translate import _
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_round

class MrpProductProduce(models.TransientModel):
    _inherit = ['mrp.product.produce']

    @api.multi
    def check_finished_move_lots(self):
        lots = self.env['stock.move.lots']
        produce_move = self.production_id.move_finished_ids.filtered(lambda x: x.product_id == self.product_id and x.state not in ('done', 'cancel'))
        if produce_move.product_id.tracking != 'none':
            if not self.lot_id:
                raise ValidationError(_('You need to provide a lot for the finished product'))
            existing_move_lot = produce_move.move_lot_ids.filtered(lambda x: x.lot_id == self.lot_id)
            if existing_move_lot:
                existing_move_lot.quantity += self.product_qty
                existing_move_lot.quantity_done += self.product_qty
            else:
                vals = {
                  'move_id': produce_move.id,
                  'product_id': produce_move.product_id.id,
                  'production_id': self.production_id.id,
                  'quantity': self.product_qty,
                  'quantity_done': self.product_qty,
                  'lot_id': self.lot_id.id,
                }
                lots.create(vals)
            for move in self.production_id.move_raw_ids:
                for movelots in move.move_lot_ids.filtered(lambda x: not x.lot_produced_id):
                    if movelots.quantity_done and self.lot_id:
                        #Possibly the entire move is selected
                        remaining_qty = movelots.quantity - movelots.quantity_done
                        if remaining_qty > 0:
                            new_move_lot = movelots.copy()
                            new_move_lot.write({'quantity':movelots.quantity_done, 'lot_produced_id': self.lot_id.id})
                            movelots.write({'quantity': remaining_qty, 'quantity_done': 0})
                        else:
                            movelots.write({'lot_produced_id': self.lot_id.id})
        return True




class stock_move_lots(models.Model):
    _inherit = 'stock.move.lots'

    picking_type = fields.Many2one('stock.picking.type', u'调拨类型')
    lot_for_copy = fields.Many2one('stock.production.lot', u'信息复制')
    lot_uom = fields.Many2one('product.uom', u'辅助单位')
    lot_uom_qty = fields.Float(u'辅助单位数量')
    lot_uom_ratio = fields.Float(u'换算率', digits=(16, 4))
    lot_lenth = fields.Char(u'全长')
    ref = fields.Char(u'追踪号')

    code = fields.Char(u"代码", size=10)
    description = fields.Char(u"说明", size=20)
    board_number = fields.Char(u"内部参考", size=20)

    # create_lot = fields.Boolean(u'创建批次',default=False)

    @api.onchange('lot_uom')
    def onchange_lot_uom(self):
        if self.lot_uom:
            self.lot_uom_ratio = self.lot_uom.factor_inv
            # if self.lot_uom.uom_type == 'bigger':
            #     self.lot_uom_ratio = self.lot_uom.factor
            # elif self.lot_uom.uom_type == 'smaller':
            #     self.lot_uom_ratio = 1 / self.lot_uom.factor
            # else:
            #     self.lot_uom_ratio = 1


    @api.onchange('lot_name')
    def onchange_lot_name(self):
        if self.lot_name and not self.lot_id:
            self.lot_name = None
        if self.lot_name and self.lot_id:
            self.lot_name = self.lot_id.display_name

    @api.onchange('lot_for_copy')
    def onchange_lot_for_copy(self):
        if self.lot_for_copy:
            self.lot_uom = self.lot_for_copy.lot_uom.id
            self.lot_uom_ratio = self.lot_for_copy.lot_uom_ratio
            self.ref = self.lot_for_copy.ref
            self.quantity_done = self.lot_uom_qty * self.lot_uom_ratio

    @api.onchange('lot_id')
    def onchange_lot_id(self):
        if self.lot_id:
            self.lot_lenth = self.lot_id.lot_lenth
            self.code = self.lot_id.code
            self.description = self.lot_id.description
            self.board_number = self.lot_id.board_number
            self.lot_uom_ratio = self.lot_id.lot_uom_ratio
            self.lot_uom = self.lot_id.lot_uom.id

    @api.onchange('lot_uom_qty', 'lot_uom_ratio')
    def onchange_lot_uom_ratio(self):
        self.quantity_done = self.lot_uom_qty * self.lot_uom_ratio

    @api.onchange('lot_lenth', 'code', 'description', 'board_number')
    def onchange_something(self):
        if self.lot_id:
            self.lot_id.lot_lenth = self.lot_lenth
            self.lot_id.code = self.code
            self.lot_id.description = self.description
            self.lot_id.board_number = self.board_number

    @api.onchange('quantity_done')
    def onchange_quantity_done(self):
        if not self.lot_id and self.quantity_done > 0:
            lot_id = self.env['stock.production.lot'].create({
                'product_id': self.operation_id.product_id.id,
                # 字段赋值
                'lot_uom': self.lot_uom.id,
                'lot_uom_ratio': self.lot_uom_ratio,
                'lot_lenth': self.lot_lenth,
                'ref': self.ref,
                'code': self.code,
                'description': self.description,
                'board_number': self.board_number,
            })
            self.lot_id = lot_id
            self.lot_name = lot_id.display_name
